#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2019/5/13 10:54
# @USER    : 717-3
# @File    : ZigZagConversion.py
# @Software: PyCharm
# @Version  : Python-3.6
# @TASK:


class Solution:
    def convert(self, s: str, numRows: int) -> str:
        """
        The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this:
         (you may want to display this pattern in a fixed font for better legibility)
        P   A   H   N

        A P L S I I G

        Y   I   R

        And then read line by line: "PAHNAPLSIIGYIR"
        Write the code that will take a string and make this conversion given a number of rows:
        string convert(string s, int numRows);

        :param s: str
        :param numRows: int
        :return: str

        Example 1:
            Input: s = "PAYPALISHIRING", numRows = 3

            Output: "PAHNAPLSIIGYIR"

        Example 2:
            Input: s = "PAYPALISHIRING", numRows = 4

            Output: "PINALSIGYAHRPI"

            Explanation:
                P     I    N

                A   L S  I G

                Y A   H R

                P     I
        """
        # if len(s) <= numRows or numRows == 1:
        #     return s
        # quotient = (len(s)-1) // (2 * numRows - 2)
        # residue = (len(s)-1) % (2 * numRows - 2)
        # if not (residue // numRows):
        #     columns = quotient * (numRows - 1) + 1
        # else:
        #     r = residue % numRows
        #     columns = quotient * (numRows - 1) + 2 + r % numRows
        # ziglist = [[[] for i in range(columns)] for i in range(numRows)]
        # for i, element in enumerate(s):
        #     quotient = i // (2 * numRows - 2)
        #     residue = i % (2 * numRows - 2)
        #     if not(residue // numRows):
        #         row = residue
        #         column = quotient * (numRows - 1)
        #     else:
        #         r = residue % numRows
        #         column = quotient * (numRows - 1) + 1 + r
        #         row = numRows - 2 - r
        #     ziglist[row][column] = element
        # func = lambda x: [y for l in x for y in func(l)] if type(x) is list else [x]
        # return "".join(func(ziglist))
        if len(s) <= numRows or numRows == 1:
            return s
        ziglist = [''] * numRows
        index, step = 0, 1
        for i in range(len(s)):
            if index <= 0:
                step = 1
            elif index >= numRows:
                index = numRows - 2
                step = -1

            ziglist[index] = ziglist[index] + s[i]
            index = index + step
        return "".join(ziglist)


if __name__ == '__main__':
    S = Solution()
    # Q6
    sample = "PAYPALISHIRING"
    rows = 2
    print(S.convert(sample, rows))
    print('done')
